<template>
  <div class="custom-search">
    <el-popover
      placement="bottom-end"
      width="500"
      trigger="manual"
      popper-class="custom-search-pop"
      v-model="visible"
      @show="popverShow"
    >
      <el-button slot="reference" size="mini" @click="showPopover" :plain="searchType === 'advance'" :type="searchType === 'advance' ? 'primary' : ''">
        <i class="V7_iconfont V7_iconV7tubiao_shaixuan"></i>
        {{ cusBtnName }}
      </el-button>
      <div class="custom-list">
        <div class="custom-title">
          <span>更多筛选</span
          ><span class="oprate-btn" @click="showCustomSearch"
            ><i class="V7_iconfont V7_iconV7tubiao_xinzeng"></i
          ></span>
        </div>
        <div class="custom-con">
          <div class="common-con-title">
            <span class="title-span"
              ><i class="V7_iconfont V7_iconV7tubiao_dian"></i>常用筛选</span
            >
          </div>
          <div class="custom-common">
            <div
              class="common-list"
              v-for="(item, index) in customList"
              :key="index"
              @click="customClick(item)"
            >
              <span>{{ item.name }}</span
              ><span class="common-list-operate">
                <i
                  class="V7_iconfont V7_iconV7tubiao_gerenshezhi-bianji1"
                  v-show="!item.default"
                  @click.stop="editCustomClick(item)"
                ></i>
                <i
                  v-show="!item.default"
                  class="V7_iconfont V7_iconV7tubiao_shanchutong"
                  @click.stop="deleteCustomClick(item)"
                ></i>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div v-show="isShowCustom" class="custom-box">
        <div class="custom-con">
          <div class="custom-con-title">
            <span class="title-span"
              ><i class="V7_iconfont V7_iconV7tubiao_dian"></i>自定义筛选</span
            >
          </div>
          <div class="common">
            <div class="common-name">
              <span class="label">名称: </span>
              <el-input
                v-model="customName"
                placeholder="请输入名称"
                size="mini"
              ></el-input>
            </div>
            <div class="common-condition">
              <div class="common-title">筛选条件</div>
              <div class="common-condition-con">
                <div v-for="(con, idx) in allConditions" :key="idx">
                  <div
                    class="common-contition-list"
                    :key="cItem.key"
                    v-for="(cItem, index) in con"
                  >
                    <span>{{ index + 1 }}.</span>
                    <el-select
                      v-model="cItem.fieldKey"
                      placeholder="请选择"
                      size="mini"
                      @change="fieldChange(cItem, index)"
                      filterable
                      style="flex: 0 0 120px"
                    >
                      <el-option
                        v-for="item in fieldList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.prop"
                      >
                      </el-option>
                    </el-select>
                    <el-select
                      v-model="cItem.fieldOperator"
                      placeholder="请选择"
                      size="mini"
                      style="flex: 0 0 95px"
                      @change="fieldSelect(cItem)"
                    >
                      <el-option
                        v-for="(item, index) in conditionList[cItem.fieldKey]
                          ? conditionList[cItem.fieldKey].condition
                          : []"
                        :key="index"
                        :label="item | getConditionText"
                        :value="item"
                      >
                      </el-option>
                    </el-select>
                    <type-component
                      ref="typeComponent"
                      :props="
                        conditionList[cItem.fieldKey] &&
                        conditionList[cItem.fieldKey].props
                          ? conditionList[cItem.fieldKey].props
                          : { label: 'name', value: '_id' }
                      "
                      :type="
                        conditionList[cItem.fieldKey]
                          ? conditionList[cItem.fieldKey].type
                          : ''
                      "
                      :condition="cItem.fieldOperator"
                      :selectList="fieldSelectList[cItem.fieldKey]"
                      v-model="cItem.fieldValue"
                      v-bind:key="cItem.key"
                    ></type-component>
                    <span @click="deleteCondition(con, index)"
                      ><i class="V7_iconfont V7_iconV7tubiao-109 delet-span"></i
                    ></span>
                  </div>
                  <div class="add-btn">
                    <span @click="conditionAdd(idx)"
                      ><i
                        class="V7_iconfont V7_iconV7tubiao_xinzeng add-span"
                      ></i
                      >添加条件</span
                    >
                  </div>
                  <el-divider content-position="center">或</el-divider>
                </div>
                <div class="add-btn">
                  <span @click="allConditionAdd"
                    ><i class="V7_iconfont V7_iconV7tubiao_xinzeng add-span"></i
                    >添加条件</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-show="isShowCustom" class="oprate">
        <el-button size="mini" @click="saveCondition">保存为常用检索</el-button>
        <el-button size="mini" type="primary" @click="searchClick"
          >检索</el-button
        >
      </div>
    </el-popover>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import typeComponent from './typeComponent.vue'
import { v4 as uuidv4 } from 'uuid'
import cloneDeep from 'lodash/cloneDeep'
import { Store } from 'vuex'
import { ElMessage } from 'element-ui/types/message'
@Component({
  name: 'custom-search',
  filters: {
    getConditionText (type) {
      // 等于  不等于 包含  不包含  为空      不为空     大于  大于等于 小于 小于等于 介于  不介于
      // 'eq', 'neq', 'in', 'nin', 'empty', 'nempty', 'gt', 'gte', 'lt', 'lte', 'between', 'nbtn'
      let label
      switch (type) {
        case 'eq':
          label = '等于'
          break;
        case 'neq':
          label = '不等于'
          break;
        case 'in':
          label = '包含'
          break;
        case 'nin':
          label = '不包含'
          break;
        case 'empty':
          label = '为空'
          break;
        case 'nempty':
          label = '不为空'
          break;
        case 'gt':
          label = '大于'
          break;
        case 'gte':
          label = '大于等于'
          break;
        case 'lt':
          label = '小于'
          break;
        case 'lte':
          label = '小于等于'
          break;
        case 'between':
          label = '介于'
          break;
        case 'nbtn':
          label = '不介于'
          break;
      }
      return label
    }
  },
  components: {
    typeComponent
  }
})
export default class CustomSearch extends Vue {
  @Prop() private customList
  @Prop() private fieldSelectList
  @Prop() private fieldList
  @Prop() private conditionList
  @Prop({ default: 'custom' }) private searchType
  private isDoc: boolean = false

  private $store: Store<any> | undefined

  private $message: ElMessage | undefined

  private visible: boolean = false

  private isShowCustom: boolean = false

  private customName = ''

  private currentCustomId = ''

  // 是否第一次
  private sign: any = false

  private $getCache

  private get cusBtnName () {
    if (this.customName) {
      return this.customName
    } else {
      return '高级'
    }
  }

  // private screenList = [[
  //   {
  //     fieldKey: '',
  //     fieldOperator: '',
  //     fieldValue: [],
  //     key: uuidv4()
  //   }
  // ]]

  private allConditions: any = [
    [
      {
        fieldKey: '',
        fieldOperator: '',
        fieldValue: [],
        key: uuidv4()
      }
    ]
  ]

  private visibleChange (evt): boolean | undefined {
    if (this.isDoc && !evt) {
      return false
    }
  }

  private mounted (): void {
    document.onclick = (evt) => {
      this.isDoc = true
    }
  }

  private fieldChange (item, index): void {
    item.fieldValue = []
    const fieldKey = item.fieldKey
    const fieldOperator = this.conditionList[fieldKey].condition[0]
    item.fieldOperator = fieldOperator
  }

  private conditionAdd (idx): void {
    this.allConditions[idx].push(
      {
        fieldKey: '',
        fieldOperator: '',
        fieldValue: [],
        key: uuidv4()
      }
    )
  }

  private allConditionAdd () {
    this.allConditions.push([
      {
        fieldKey: '',
        fieldOperator: '',
        fieldValue: [],
        key: uuidv4()
      }
    ])
  }

  private deleteCondition (item, index): void {
    item.splice(index, 1)
    if (item && !item.length) {
      this.allConditions = this.allConditions.filter(v => v.length)
    }
  }

  private searchClick (): void {
    if (this.checkValue()) {
      this.$emit('handleSearch', this.checkValue())
    }
  }

  private saveCondition (): boolean | undefined {
    if (!this.customName) {
      (this.$message as ElMessage)({ message: '请输入自定义检索名称！', type: 'error' })
      return false
    }
    if (this.checkValue()) {
      this.$emit('saveCondition', { name: this.customName, advanceQuery: this.checkValue(), currentCustomId: this.currentCustomId })
      this.isShowCustom = false
      this.currentCustomId = ''
    }
  }

  private popverShow (): void {
    if (!this.sign) {
      this.sign = true
      this.$emit('popverShow')
      this.initSelectList()
    }
    document.addEventListener('click', this.clickFun)
  }

  private clickFun (e): void {
    let isFocus = false;
    (this.$refs as any).typeComponent.some((item) => {
      if (item.isFocus) {
        isFocus = true
        return true
      }
    })
    if (!this.$el.contains(e.target)) {
      if (!isFocus) {
        this.visible = false
      }
    }
  }

  private showPopover (): void {
    this.visible = true
  }

  private initSelectList (): void {
    const getVoiceList = this.$getCache('/call/action/general/query', ['ivrList'], false)
    const getRegionDict = this.$getCache('/base/action/general/cache/query', ['cdrRegion'], false)
    Promise.all([getVoiceList, getRegionDict]).then(([voiceLibraryList, regionDict]) => {
      this.fieldSelectList.ivrId = voiceLibraryList.ivrList || []
      this.fieldSelectList.customerCountry = (regionDict.cdrRegion && regionDict.cdrRegion.options && regionDict.cdrRegion.options[0].options) || []
      this.fieldSelectList.displayNumberArea = (regionDict.cdrRegion && regionDict.cdrRegion.options && regionDict.cdrRegion.options[0].options) || []
    })
  }

  private showCustomSearch (): void {
    this.customName = ''
    this.currentCustomId = ''
    this.allConditions = [
      [
        {
          fieldKey: '',
          fieldOperator: '',
          fieldValue: [],
          key: uuidv4()
        }
      ]
    ]
    this.isShowCustom = true
  }

  private customClick (item): void {
    this.customName = item.name
    this.currentCustomId = item._id
    this.isShowCustom = false
    this.$emit('handleSearch', item.advanceQuery)
  }

  private editCustomClick (item): void {
    this.currentCustomId = item._id
    this.customName = item.name
    this.$set(this, 'screenList', cloneDeep(item.advanceQuery))
    this.isShowCustom = true
  }

  private deleteCustomClick (item): void {
    this.$emit('deleteCustomClick', item)
    if (this.currentCustomId === item._id) {
      this.isShowCustom = false
      this.currentCustomId = ''
      this.customName = ''
    }
  }

  private checkValue (): boolean | void {
    let check = false
    const checkList = cloneDeep(this.allConditions)
    checkList[0].some((item, index) => {
      if (item.key) {
        delete item.key
      }
      if (item.fieldOperator === 'between') {
        if (!item.fieldValue[1] || item.fieldValue[1].length === 0) {
          check = true
          return true
        }
      }
      // 为空 不为空 不需要值
      if ((item.fieldOperator !== 'empty' && item.fieldOperator !== 'nempty')) {
        if (!item.fieldValue[0] || item.fieldValue[0].length === 0) {
          check = true
          return true
        }
      }
      // if (item.fieldKey === 'sessionTags') {
      //   const arr: any = []
      //   if (item.fieldValue[0]) {
      //     item.fieldValue[0].forEach(tagItem => {
      //       arr.push(tagItem[tagItem.length - 1])
      //     })
      //   }
      //   item.fieldValue = [arr, '']
      // }
    })
    if (check || checkList.length === 0) {
      (this.$message as ElMessage)({ message: '存在空值条件，请检查！', type: 'error' })
      return false
    }
    return checkList
  }

  private fieldSelect (item): void {
    this.$set(item, 'fieldValue', [])
  }

  public hide (): void {
    this.visible = false
  }
}
</script>

<style lang="stylus" scoped>
.el-divider__text
  font-size 12px
.oprate
  display flex
  justify-content flex-end
.common-title
  padding 15px
  font-size 12px
.common-condition-con
  max-height 150px
  overflow-y scroll
  padding 0px 15px 15px
.common-con-title
  display flex
  align-items center
  padding 10px 15px 10px
  span
    font-size 12px
  .V7_iconfont
    color $c-main
    font-size 12px
.custom-con-title
  display flex
  align-items center
  padding 10px 15px 10px
  border-top 1px solid $border-main
  span
    font-size 12px
  .V7_iconfont
    color $c-main
    font-size 12px
.custom-common
  max-height 100px
  overflow-y scroll
  padding 0 0 10px
  .common-list
    padding 5px 15px 5px
    display flex
    flex-direction row
    justify-content space-between
    align-items center
    cursor pointer
    font-size 12px
  .common-list-operate
    display none
  .V7_iconfont
    margin-right 10px
    color $icon-gray
    font-size 12px
    cursor pointer
  .common-list:hover
    background #F3F6F9
    .common-list-operate
      display block
.add-span
  margin-right 4px
.title-span
  color $fc-gray2
.delet-span
  cursor pointer
  &:hover
    color $c-danger
.oprate
  padding 10px 15px 10px
.common-contition-list
  display flex
  align-items center
  margin-bottom 10px
.common-contition-list > *
  margin-right 8px
.common-name
  display flex
  align-items center
  padding 0 15px 0
  .label
    display block
    white-space nowrap
    margin-right 8px
    font-size 12px
.custom-list
  width 100%
  font-size 12px
  color $fc-gray3
  .custom-title
    padding 10px 15px 10px
    font-size 14px
    font-weight 600
    color $fc-gray2
    display flex
    justify-content space-between
    border-bottom 1px solid $border-main
    .oprate-btn
      .V7_iconfont
        font-size 12px
        color $c-main
        cursor pointer
.custom-box
  width 100%
  color $fc-gray3
  .add-btn
    color $c-main
    cursor pointer
    .V7_iconfont
      font-size 10px
  .custom-con
    .oprate-btn
      .V7_iconfont
        font-size 12px
        color $c-main
        cursor pointer
.custom-search
  margin 0 10px 16px 0
  .V7_iconfont
    font-size 12px
</style>
<style lang='stylus'>
.custom-box
  .el-dropdown-menu
    padding 0
.custom-search-pop
  padding 0
</style>
